package model

import (
	"ginblog/utils/errmsg"
	"github.com/jinzhu/gorm"
)

type Fan struct {
	User User `gorm:"foreignkey:Uid" json:"user,omitempty"`
	Follow User `gorm:"foreignkey:FollowUid"`
	BaseModel
	FollowUid     int    `gorm:"type:int;not null" json:"follow_uid"`
	Uid     int    `gorm:"type:int;not null" json:"uid"`
	Status int `gorm:"type:int; not null" json:"status"`
}


// 查询用户是否关注了这个用户
func IsFollow(uid int , followUid int)(Fan,int) {
	var fan Fan
	db.Select("id,status").Where(&Fan{FollowUid: followUid, Uid: uid}).First(&fan)
	if fan.ID > 0  {
		return fan,errmsg.SUCCSE
	}
	return fan,errmsg.ERROR
}

// 新增关注
func CreateFan(data *Fan)int  {
	err := db.Create(&data).Error
	if err !=nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCSE
}

// 取消关注更新
func SaveFan(data *Fan,uid int) int  {
	var fan Fan

	var maps = make(map[string]interface{})
	maps["status"] = data.Status
	err = db.Debug().Model(&fan).Where(&Fan{FollowUid: data.FollowUid, Uid: uid}).Update(maps).Error
	if err != nil{
		return errmsg.ERROR
	}
	return errmsg.SUCCSE
}

//  查询我的关注列表
func GetFollowList(uid int, pageSize int, pageNum int) ([]Fan, int, int) {
	var fanList []Fan
	var total int

	err = db.Preload("Follow").Limit(pageSize).Offset((pageNum - 1) * pageSize).Where("uid = ?", uid).Find(&fanList).Count(&total).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, errmsg.ERROR, 0
	}
	return fanList, errmsg.SUCCSE, total
}

//  查询我的粉丝列表
func GetFanList(uid int, pageSize int, pageNum int) ([]Fan, int, int) {
	var fanList []Fan
	var total int

	err = db.Preload("User").Limit(pageSize).Offset((pageNum - 1) * pageSize).Where("follow_uid = ?", uid).Find(&fanList).Count(&total).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, errmsg.ERROR, 0
	}
	return fanList, errmsg.SUCCSE, total
}


